package org.colour.amber.rest.advice;

import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.colour.amber.exception.RestException;
import org.colour.amber.rest.api.RestResponse;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 自定义ExceptionHandler，专门处理Restful异常.
 *
 * @author jasonfu
 */
@Slf4j
@ControllerAdvice
public class RestExceptionHandler {

    /** 处理RestException. */
    @ExceptionHandler(value = {RestException.class})
    public final ResponseEntity<?> handleException(RestException ex) {
        log.error("发生异常", ex);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>(RestResponse.fail(ex.getMessage()), headers, ex.status);
    }

    /** 处理MethodArgumentNotValidException. */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public final ResponseEntity<?> handleException(MethodArgumentNotValidException ex) {
        log.error("发生异常", ex);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        BindingResult bindingResult = ex.getBindingResult();
        String errorMsg = bindingResult.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return new ResponseEntity<>(RestResponse.fail(errorMsg), headers, HttpStatus.BAD_REQUEST);
    }
}
